<template>
  <div class="depart-tree">
    <a-spin tip="Loading..." :spinning="false" v-show="toggle">
      <a-input-search v-model="searchValue" style="margin-bottom: 1px" placeholder="请输入部门名称按回车进行搜索" />
      <slot></slot>
      <a-empty v-if="filterTreeData.length===0"></a-empty>
      <a-tree
        v-else
        checkable
        class="my-depart-tree"
        :treeData="filterTreeData"
        :checkStrictly="checkStrictly"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand"
        :autoExpandParent="autoExpandParent"
        :expandedKeys="expandedKeys"
        :checkedKeys="checkedKeys">
      </a-tree>
    </a-spin>
    <div class="menu-fold" :style="!toggle?{top:'0'}:''">
      <a-tooltip v-model="visible" placement="top" :title="toggle?'收起':'展开'">
        <a-icon :type="toggle?'menu-fold':'menu-unfold'" @click="setToggle" />
      </a-tooltip>
      <!-- <a-dropdown :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
        </a-menu>
        <a-tooltip placement="topLeft">
          <template slot="title">
            <span>树操作</span>
          </template>
          <a-icon type="align-right" />
        </a-tooltip>
      </a-dropdown> -->
    </div>
  </div>
</template>

<script>
import { queryDepartTreeList } from '@/api/api'
import { Empty } from 'ant-design-vue';
export default {
  name: 'departTree',
  props:['modalWidth','multi','rootOpened','departId', 'store', 'text','treeOpera', 'departType'],
  data() {
    return {
      treeData:[
        {
          title: 'SJSK-PC端',
          key: 'SJSK-PC端',
          id:"SJSK-PC端",
          value:"SJSK-PC端"
        },
        {
          title: '智慧禁毒APP',
          key: '智慧禁毒APP',
          id:"智慧禁毒APP",
          value:"智慧禁毒APP"
        },
        {
          title: '椰风送暖APP',
          key: '椰风送暖APP',
          id:"椰风送暖APP",
          value:"椰风送暖APP"
        }
      ],
      autoExpandParent:true,
      expandedKeys:[],
      dataList:[],
      checkedKeys:[],
      checkedRows:[],
      searchValue:"",
      checkStrictly: true,
      toggle: true,
      visible: false
    }
  },
  created() {
    this.loadDepart()
  },
  watch: {
    departId(){
      this.initDepartComponent()
    }
  },
  computed:{
    filterTreeData(){
      if(!this.searchValue){
        return this.treeData
      }
      let filter = []
      this.dataList.forEach((item) => {
        if (item.title.includes(this.searchValue)) {
          filter.push(Object.assign({}, item, {children: null, isLeaf: true}))
        }
      })
      return filter
    },
  },
  methods: {
    // show(){
    //   this.visible=true
    //   this.checkedRows=[]
    //   this.checkedKeys=[]
    // },
    loadDepart(){
      // 这个方法是找到所有的部门信息
      // let obj = this.departType? {departType: this.departType}: {departType: 1}
      // queryDepartTreeList(obj).then(res=>{
      //   if(res.success){
      //     let arr = [...res.result]
      //     this.reWriterWithSlot(arr)
      //     this.treeData = arr
      //     console.log(arr)
      //     this.initDepartComponent()
      //     if(this.rootOpened){
      //       this.initExpandedKeys(res.result)
      //     }
      //   }
      // })
    },
    initDepartComponent(flag){
      let arr = []
      //该方法两个地方用 1.visible改变事件重新设置选中项 2.组件编辑页面回显
      let fieldName = flag==true?'key':this.text
      if(this.departId){
        let arr2 = this.departId.split(',')
        for(let item of this.dataList){
          if(arr2.indexOf(item[this.store])>=0){
            arr.push(item[fieldName])
          }
        }
      }
      if(flag==true){
        this.checkedKeys = [...arr]
      }else{
        this.$emit("initComp", arr.join(','))
      }
    },
    reWriterWithSlot(arr){
      for(let item of arr){
        if(item.children && item.children.length>0){
          this.reWriterWithSlot(item.children)
          let temp = Object.assign({},item)
          temp.children = {}
          this.dataList.push(temp)
        }else{
          this.dataList.push(item)
          item.scopedSlots={ title: 'title' }
        }
      }
    },
    initExpandedKeys(arr){
      if(arr && arr.length>0){
        let keys = []
        for(let item of arr){
          if(item.children && item.children.length>0){
            keys.push(item.id)
          }
        }
        this.expandedKeys=[...keys]
        console.log(2, this.expandedKeys)
        //全部keys
        //this.allTreeKeys = [...keys]
      }else{
        this.expandedKeys=[]
        console.log(1, this.expandedKeys)
        //this.allTreeKeys = []
      }
    },
    onCheck (checkedKeys,info) {
      if(!this.multi){
        let arr = checkedKeys.checked.filter(item => this.checkedKeys.indexOf(item) < 0)
        this.checkedKeys = [...arr]
        this.checkedRows = (this.checkedKeys.length === 0) ? [] : [info.node.dataRef]
      }else{
        if(this.checkStrictly){
          this.checkedKeys = checkedKeys.checked
        }else{
          this.checkedKeys = checkedKeys
        }
        this.checkedRows = this.getCheckedRows(this.checkedKeys)
      }
      this.handleSubmit()
      console.log(1)
    },
    onSelect(selectedKeys,info) {
      //取消关联的情况下才走onSelect的逻辑
      if(this.checkStrictly){
        let keys = []
        keys.push(selectedKeys[0])
        if(!this.checkedKeys || this.checkedKeys.length===0 || !this.multi){
          this.checkedKeys = [...keys]
          this.checkedRows=[info.node.dataRef]
        }else{
          let currKey = info.node.dataRef.key
          if(this.checkedKeys.indexOf(currKey)>=0){
            this.checkedKeys = this.checkedKeys.filter(item=> item !==currKey)
          }else{
            this.checkedKeys.push(...keys)
          }
        }
        this.checkedRows = this.getCheckedRows(this.checkedKeys)
      }
      this.handleSubmit()
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    handleSubmit(){
      if(!this.checkedKeys || this.checkedKeys.length==0){
        this.$emit("ok",'')
      }else{
        let checkRow = this.getCheckedRows(this.checkedKeys)
        let keyStr = this.checkedKeys.join(",")
        let adminDivision = checkRow.length>0? checkRow[0].adminDivision: null
        // this.$emit("ok", checkRow, keyStr)
        this.$emit("ok", checkRow, adminDivision)
      }
      // this.handleClear()
    },
    handleCancel(){
      this.handleClear()
    },
    handleClear(){
      this.visible=false
      this.checkedKeys=[]
    },
    getParentKey(currKey,treeData){
      let parentKey
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i]
        if (node.children) {
          if (node.children.some(item => item.key === currKey)) {
            parentKey = node.key
          } else if (this.getParentKey(currKey, node.children)) {
            parentKey = this.getParentKey(currKey, node.children)
          }
        }
      }
      return parentKey
    },
    // 根据 checkedKeys 获取 rows
    getCheckedRows(checkedKeys) {
      const forChildren = (list, key) => {
        for (let item of list) {
          if (item.id === key) {
            return item
          }
          if (item.children instanceof Array) {
            let value = forChildren(item.children, key)
            if (value != null) {
              return value
            }
          }
        }
        return null
      }

      let rows = []
      for (let key of checkedKeys) {
        let row = forChildren(this.treeData, key)
        if (row != null) {
          rows.push(row)
        }
      }
      return rows
    },
    switchCheckStrictly (v) {
      if(v==1){
        this.checkStrictly = false
      }else if(v==2){
        this.checkStrictly = true
      }
    },
    setToggle() {
      this.toggle = !this.toggle
      this.visible = false
      this.$emit('toggleBool', this.toggle)
    }
  }
}
</script>
<style lang="less" scoped>
.depart-tree {
  padding-bottom: 10px;
  min-height: 600px;
  margin: 6px;
  position: relative;
  .menu-fold {
    position: absolute;
    top: 42px;
    right: 4px;
  }
  // 限制部门选择树高度，避免部门太多时点击确定不便
  .my-depart-tree{
    height: calc(100vh - 120px);
    overflow-y: auto;
  }
}
</style>
